﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;

namespace SPContrib
{
    /// <summary>
    /// A utility class the includes System.Linq.Expressions for accessing members on the type
    /// </summary>
    public static class From<TType>
    {

        /// <summary>
        /// Returns a method that represents an expression that can read internal properties
        /// </summary>
        /// <typeparam name="TType">the type to access</typeparam>
        /// <typeparam name="TPropertyType">the expected return type of the property</typeparam>
        /// <param name="property">the name of the property</param>
        public static Func<TType, TPropertyType> ReadProperty<TPropertyType>(string property)
        {
            ParameterExpression param = Expression
                                    .Parameter(typeof(TType), "arg");

            MemberExpression member = Expression
                                        .Property(param, property);

            LambdaExpression lambda = Expression
                                        .Lambda(typeof(Func<TType, TPropertyType>), member, param);

            Func<TType, TPropertyType> compiled = (Func<TType, TPropertyType>)lambda.Compile();
            return compiled;
        }

    }
}
